
import 'package:auntserver/model/entitys.dart';
import 'package:auntserver/net_api/aunt_datas.dart';
import 'package:auntserver/utils/aunt_utils.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../app_constants.dart';

class WorkBenchPage extends StatefulWidget{
  @override
  _WorkBenchState createState() => _WorkBenchState();
}

class _WorkBenchState extends State<WorkBenchPage> with AutomaticKeepAliveClientMixin{
  AuntEntityUserinfo _auntUserinfo;
  List<OrderPoolEntityOrderList> orderPoolList = [];
  RefreshController _refreshController =
  RefreshController(initialRefresh: true);

  Future _onRefresh() async {
    // monitor network fetch
    await AuntData.requestOrderPoolList(
        _auntUserinfo.userid.toString(),
        _auntUserinfo.accesstoken,
        IdentityStatus.aunt.index.toString(),
        "120.202841",
        "29.733935")
        .then((value) {
      if (mounted) {
        setState((){
          orderPoolList.clear();
          if (value is OrderPoolEntity) {
            _refreshController.refreshCompleted();
            orderPoolList.addAll(value.orderList);
          } else {
            _refreshController.refreshFailed();
          }
        });
      }
    });
    // if failed,use refreshFailed()
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
  void _onLoading() async {
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    _auntUserinfo = Provider
        .of<AuntEntity>(context)
        .userinfo;
    return SafeArea(
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: ScreenUtil().getWidth(20)),
            child: SizedBox(
              height: ScreenUtil().getHeight(44),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  MissionSwitch(),
                  Icon(Icons.phonelink_lock),
                ],
              ),
            ),
          ),
          Expanded(
            child: Container(
              color: AuntColors.ABACKGROUND,
              padding:
              EdgeInsets.symmetric(horizontal: ScreenUtil().getWidth(20)),
              child: SmartRefresher(
                enablePullDown: true,
                enablePullUp: true,
                header: WaterDropHeader(),
                footer: CustomFooter(
                  builder: (BuildContext context, LoadStatus mode) {
                    Widget body;
                    if (mode == LoadStatus.idle) {
                      body = Text("pull up load");
                    } else if (mode == LoadStatus.loading) {
                      body = CupertinoActivityIndicator();
                    } else if (mode == LoadStatus.failed) {
                      body = Text("Load Failed!Click retry!");
                    } else if (mode == LoadStatus.canLoading) {
                      body = Text("release to load more");
                    } else {
                      body = Text("No more Data");
                    }
                    return Container(
                      height: 55.0,
                      child: Center(child: body),
                    );
                  },
                ),
                controller: _refreshController,
                onRefresh: _onRefresh,
                onLoading: _onLoading,
                child: ListView.builder(
                  itemCount: orderPoolList.length + 1,
                  itemBuilder: (BuildContext context, int index) {
                    return index == 0
                        ? buildButtonGroup()
                        : OrderPoolItem(orderPoolList[index - 1]);
                  },
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Column buildButtonGroup() {
    return Column(
      children: [
        SizedBox(height: ScreenUtil().getHeight(20)),
        Row(
          children: [
            Expanded(
              flex: 1,
              child: buildFourButton(
                  content: "活到老学到老>",
                  title: "考试中心",
                  img: "work_bench_icon1",
                  function: () {
                    print("考试中心" + OrderCategory.SecondsKill.index.toString());
                  }),
            ),
            SizedBox(
              width: ScreenUtil().getWidth(20),
            ),
            Expanded(
              flex: 1,
              child: buildFourButton(
                  content: "做任务即刻赚现金>",
                  title: "做任务",
                  img: "work_bench_icon2",
                  function: () {
                    print("做任务");
                  }),
            ),
          ],
        ),
        SizedBox(height: ScreenUtil().getHeight(16)),
        Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: buildFourButton(
                  content: "邀请姐妹发家致富>",
                  title: "邀请阿姨",
                  img: "work_bench_icon3",
                  function: () {
                    print("邀请阿姨");
                  }),
            ),
            SizedBox(
              width: ScreenUtil().getWidth(20),
            ),
            Expanded(
              flex: 1,
              child: buildFourButton(
                  content: "查看个人信息>",
                  title: "个人中心",
                  img: "work_bench_icon4",
                  function: () {
                    print("个人中心");
                  }),
            ),
          ],
        ),
        SizedBox(height: ScreenUtil().getHeight(16)),
      ],
    );
  }

  Widget buildFourButton({@required String img,
    @required String title,
    @required String content,
    @required Function function}) {
    return GestureDetector(
      onTap: function,
      child: AspectRatio(
          aspectRatio: 1.55,
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Colors.white,
              borderRadius:
              BorderRadius.all(Radius.circular(ScreenUtil().getWidth(14))),
            ),
            padding: EdgeInsets.all(ScreenUtil().getWidth(12)),
            child: Flex(
              direction: Axis.vertical,
              children: [
                Expanded(
                  flex: 44,
                  child: Row(
                    children: [
                      Image.asset(Utils.getImgPath(img)),
                      SizedBox(
                        width: ScreenUtil().getWidth(10),
                      ),
                      Text(title),
                    ],
                  ),
                ),
                Expanded(
                    flex: 26,
                    child: Align(
                      child: Text(content),
                      alignment: Alignment.centerLeft,
                    ))
              ],
            ),
          )),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

//是否接单开关
class MissionSwitch extends StatefulWidget {
  @override
  _MissionSwitchState createState() => _MissionSwitchState();
}

class _MissionSwitchState extends State<MissionSwitch> {
  final double value0 = 0.0;
  final double value1 = ScreenUtil().getWidth(75);
  final double value2 = ScreenUtil().getWidth(150);
  final double swheight = ScreenUtil().getHeight(34);
  final int pageSwitchAnimatedTime = 200;
  double value = 0.0;
  bool open = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Stack(
        children: <Widget>[
          GestureDetector(
            child: Container(
              height: swheight,
              width: value2,
              decoration: BoxDecoration(
                color: Color(0xffF3F4F5),
                borderRadius: BorderRadius.circular(50),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Text(
                    '开始接单',
                    style: TextStyle(
                      color: Color(0xff999999),
                      fontSize: 14,
                    ),
                  ),
                  Text(
                    '停止接单',
                    style: TextStyle(
                      color: Color(0xff999999),
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
            onTap: missionSwitch,
          ),
// 滑块
          AnimatedPositioned(
            left: this.value,
            duration: Duration(milliseconds: pageSwitchAnimatedTime),
            child: Container(
              width: value1,
              height: swheight,
              decoration: BoxDecoration(
                color: AuntColors.AORANGE,
                borderRadius: BorderRadius.circular(50),
              ),
              child: Center(
                child: Text(
                  open ? '停止接单' : '开始接单',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void missionSwitch() {
    setState(() {
      if (!open) {
        this.value = value1;
        open = true;
      } else {
        open = false;
        this.value = value0;
      }
    });
  }
}

class OrderPoolItem extends StatelessWidget {
  final OrderPoolEntityOrderList _orderPool;
  final bool haveTopImg;

  OrderPoolItem(this._orderPool, {this.haveTopImg = false});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: ScreenUtil().getHeight(50),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(_orderPool.title),
                  Text(_orderPool.distance),
                ],
              ),
              _buildLine("上门时间", _orderPool.addtime),
              _buildLine("预计收入", _orderPool.priceStr),
              _buildLine("预计时长", _orderPool.totime),
              buildOrderPoolButtonRow(_orderPool.orderType),
            ],
          ),
          Align(
            alignment: Alignment.topCenter,
            child: Container(
              height: ScreenUtil().getHeight(35),
              width: ScreenUtil().getWidth(120),
              child: Center(child: Text("订单池")),
              decoration: BoxDecoration(
                  color: AuntColors.AORANGE,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(100),
                      bottomRight: Radius.circular(100))),
            ),
          )
        ],
      ),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      padding: EdgeInsets.only(
          bottom: ScreenUtil().getHeight(14),
          right: ScreenUtil().getWidth(14),
          left: ScreenUtil().getWidth(14)),
      margin: EdgeInsets.only(bottom: ScreenUtil().getHeight(14)),
    );
  }

  Row buildOrderPoolButtonRow(int type) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        RaisedButton(
          color: AuntColors.AORANGE,
          textColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(20)),
          ),
          onPressed: () {},
          child: Text("接单"),
        ),
        RaisedButton(
          color: AuntColors.AORANGE,
          textColor: Colors.white,
          onPressed: () {},
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(20)),
          ),
          child: Text("拒单"),
        ),
      ],
    );
  }

  /*
    闪购、计时类保洁、套餐展示预计收入
    有计时的展示预约时长
    维修展示上门费，其他不展示收入
    服务地址：传过来与定位地址拼接重合
    */
  Row _buildLine(String title, String content) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Icon(
          Icons.circle,
          color: AuntColors.AORANGE,
          size: ScreenUtil().getWidth(10),
        ),
        SizedBox(
          width: ScreenUtil().getWidth(10),
        ),
        Text("$title:$content"),
      ],
    );
  }

Row _buildMultipleLine(String title, String content) {
  return Row(
    mainAxisAlignment: MainAxisAlignment.start,
    children: [
      Icon(
        Icons.circle,
        color: AuntColors.AORANGE,
        size: ScreenUtil().getWidth(10),
      ),
      SizedBox(
        width: ScreenUtil().getWidth(10),
      ),
      Text(_orderPool.address),
    ],
  );
}


}